<template>
    <div ref="chartContainer" :style="{ width: width, height: height }"></div>
  </template>
  
  <script>
  import * as echarts from "echarts";
  import { ref, watch, onMounted, onUnmounted } from "vue";
  
  export default {
    props: {
      options: {
        type: Object,
        required: true, // 图表配置项
      },
      width: {
        type: String,
        default: "100%", // 图表宽度
      },
      height: {
        type: String,
        default: "400px", // 图表高度
      },
    },
    setup(props) {
      const chartContainer = ref(null); // 图表容器的 DOM 引用
      let chartInstance = null; // 图表实例
  
      // 初始化图表
      const initChart = () => {
        if (chartContainer.value) {
          chartInstance = echarts.init(chartContainer.value); // 初始化实例
          chartInstance.setOption(props.options); // 设置初始配置
        }
      };
  
      // 监听 options 变化
      watch(
        () => props.options,
        (newOptions) => {
          if (chartInstance) {
            chartInstance.setOption(newOptions); // 更新图表数据
          }
        },
        { deep: true }
      );
  
      // 生命周期管理
      onMounted(() => {
        initChart();
        window.addEventListener("resize", resizeChart);
      });
  
      onUnmounted(() => {
        if (chartInstance) {
          chartInstance.dispose(); // 销毁图表实例
        }
        window.removeEventListener("resize", resizeChart);
      });
  
      // 自适应图表大小
      const resizeChart = () => {
        if (chartInstance) {
          chartInstance.resize();
        }
      };
  
      return {
        chartContainer,
      };
    },
  };
  </script>
  
  <style scoped>
  /* 可根据需要调整样式 */
  </style>